package com.jeecg.p3.system.web.app;


import com.jeecg.p3.base.util.*;
import com.jeecg.p3.commonweixin.entity.MyJwWebJwid;
import com.jeecg.p3.system.base.BaseController;
import com.jeecg.p3.system.entity.JwSystemUser;
import com.jeecg.p3.system.service.JwSystemAuthService;
import com.jeecg.p3.system.service.JwWebJwidService;
import com.jeecg.p3.system.service.MyJwWebJwidService;
import com.jeecg.p3.system.util.Constants;
import com.jeecg.p3.system.vo.LoginUser;
import com.jeecg.p3.system.vo.Menu;
import com.jeecg.p3.system.vo.WeixinAccountDto;
import com.jeecg.p3.system.web.SystemController;
import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.MD5Util;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 手机端登录相关接口
 */
@Controller
@RequestMapping("/app/login")
public class AppLoginController extends BaseController {
    public static final Logger logger = LoggerFactory.getLogger(AppLoginController.class);

    @Autowired
    private JwWebJwidService jwidService;
    @Autowired
    private JwSystemAuthService jwSystemAuthService;
    @Autowired
    private MyJwWebJwidService myJwWebJwidService;

    /**
     * 手机端登录
     * @param username
     * @param password
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/login",method ={RequestMethod.GET, RequestMethod.POST})
    public AjaxJson login(String username, String password,HttpServletRequest request) throws Exception{
        AjaxJson j = new AjaxJson();
        try {
            LoginUser user = userService.queryUserByUserId(username);
            if (user == null) {
                j.setSuccess(false);
                j.setMsg("登录账号【" + username + "】，在系统中不存在！！");
                return j;
            }
            // 验证用户密码是否正确
            String passwordEncode = MD5Util.MD5Encode(password, "utf-8");
            if (passwordEncode != null && passwordEncode.equals(user.getPassword())
                    && Constants.USER_NORMAL_STATE.equals(user.getUserStat())) {
                JwSystemUser systemUser = userService.queryById(Long.valueOf(user.getId()));
                //如果不为管理员（为顾问），并且激活状态未激活则返回对象让前段去激活，否则返回成功直接跳转到主页
                List<WeixinAccountDto> jwids = new ArrayList<WeixinAccountDto>();
                // 验证通过,根据userid查询捷微列表
                jwids = jwidService.queryJwWebJwidByUserId(username);
                List<Menu> menuTree = jwSystemAuthService.getMenuTree(user.getUserId());

                /*request.getSession().setAttribute(Constants.SYSTEM_JWID, jwids.get(0).getJwid());
                request.getSession().setAttribute(Constants.SYSTEM_JWIDNAME, jwids.get(0).getName());
                request.getSession().setAttribute(Constants.SYSTEM_USERID, user.getUserId());
                request.getSession().setAttribute(Constants.OPERATE_WEB_LOGIN_USER, user);*/
                if(!Constants.stateActvi.equals(systemUser.getAdmin())
                        && !Constants.stateActvi.equals(systemUser.getState())) {
                    logger.info("登录验证成功：用户【" + username + "】权限验证通过");
                    j.setSuccess(true);
                    Map<String, Object> map = new HashMap<>();
                    map.put("needActvi", "1");//设置需要激活
                    map.put("uid", user.getId());//返回用户id
                    map.put("jwid", jwids.get(0).getJwid());//返回用户id
                    map.put("menu", menuTree);
                    j.setObj(map);
                    j.setMsg("未激活，请激活！");
                } else {
                    j.setSuccess(true);
                    Map<String, Object> map = new HashMap<>();
                    map.put("jwid", jwids.get(0).getJwid());//返回用户id
                    map.put("needActvi", "0");//不需要激活
                    map.put("menu", menuTree);
                    j.setObj(map);
                    j.setMsg("登录验证成功!");
                }
                return j;
            } else {
                logger.info("用户【" + username + "】不存在或者密码错误！！");
                j.setMsg("用户【" + username + "】不存在或者密码错误！！");
                j.setSuccess(false);
                return j;
            }
        } catch (Exception e) {
            j.setMsg("登录异常请联系管理员!");
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 跳转到认证界面
     * @param jwid
     * @param username
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/auth", method = { RequestMethod.GET, RequestMethod.POST })
    public void login(String jwid, String username, String uid, HttpServletRequest request,
                      HttpServletResponse response) throws Exception
    {
        VelocityContext velocityContext = new VelocityContext();
        String viewName = "system/back/login/auth.html";
        velocityContext.put("jwid", jwid);
        velocityContext.put("uid", uid);
        velocityContext.put("username", username);
        ViewVelocity.view(request, response, viewName, velocityContext);
    }

    @RequestMapping(value = "/toIndex", method = { RequestMethod.GET, RequestMethod.POST })
    public void toIndex(HttpServletRequest request,
                      HttpServletResponse response) throws Exception
    {
        /*String url = ComCode.authorize + "appid=" + ComCode.appid + "&redirect_uri=" + ComCode.systemUrl + "/app/login/index.do"
                + ComCode.baseUrl;
        logger.info("tourl: " + url);
        HttpUtil.get(url);*/
        VelocityContext velocityContext = new VelocityContext();
        String viewName = "system/back/login/toIndex.html";
        ViewVelocity.view(request, response, viewName, velocityContext);
    }

    /**
     * 跳转到主页
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/index", method = { RequestMethod.GET, RequestMethod.POST })
    public void index(HttpServletRequest request,
                        HttpServletResponse response) throws Exception
    {
        logger.info("----------index----start-----------");
        VelocityContext velocityContext = new VelocityContext();
        WxUserInfo wxUserInfo = getWxUserInfo(request);
        if(wxUserInfo == null || StringUtils.isEmpty(wxUserInfo.getOpenid())) {
            AjaxJson j = WxUtils.getWxUserDetail(request);
            if(j.isSuccess()) {
                wxUserInfo = (WxUserInfo) j.getObj();
                request.getSession().setAttribute(Constants.wxInfo, j.getObj());
            } else {
                String toUrl = ComCode.systemUrl + "/app/login/index.do";
                String url = ComCode.authorize + "appid=" + ComCode.appid + "&redirect_uri="
                        + URLEncoder.encode(toUrl, "UTF-8") + ComCode.userinfoUrl;
                response.sendRedirect(url);
                return;
            }
        }
        /*String code = request.getParameter("code");
        if(StringUtils.isNotEmpty(code)) {
            logger.info("------检测到有code进行再次跳转！！！");
            String toUrl = ComCode.systemUrl + "/app/login/index.do";
            response.sendRedirect(toUrl);
            return;
        }*/
        logger.info("openId : " + wxUserInfo.getOpenid());
        LoginUser loginUser = this.userService.queryUserByOpenid(wxUserInfo.getOpenid());
        String viewName = "";
        if(loginUser == null) {
            logger.info("----loginUser is null-----");
            viewName = "system/back/login/index.html";//跳转到H5登录界面
            ViewVelocity.view(request, response, viewName, velocityContext);
        } else {
            List<WeixinAccountDto> jwids = jwidService.queryJwWebJwidByUserId(loginUser.getUserId());
            if(jwids != null && jwids.size() > 0) {
                request.getSession().setAttribute(Constants.SYSTEM_JWID, jwids.get(0).getJwid());
                request.getSession().setAttribute(Constants.SYSTEM_JWIDNAME, jwids.get(0).getName());
            }
            //状态已激活则直接跳转到主页
            if(Constants.stateActvi.equals(loginUser.getState())) {
                request.getSession().setAttribute(Constants.SYSTEM_USERID, loginUser.getUserId());
                request.getSession().setAttribute(Constants.OPERATE_WEB_LOGIN_USER, loginUser);
                List<Menu> menuTree = jwSystemAuthService.getMenuTree(loginUser.getUserId());
                velocityContext.put(Constants.OPERATE_WEB_MENU_TREE, menuTree);
                viewName = SystemController.homePath;
                MyJwWebJwid myJwWebJwid = myJwWebJwidService.queryByJwid(Constants.wxid);
                String jsapi_ticket = myJwWebJwid.getJsApiTicket();
                String url = ComCode.systemUrl + "/app/login/index.do";
                Map<String, String> map = JsSignUtil.sign(jsapi_ticket, url);
                velocityContext.put("wx",map);
                velocityContext.put("appId", ComCode.appid);
                ViewVelocity.view(request, response, viewName, velocityContext);
            }
            //未激活跳转倒授权激活界面
            else {
                viewName = "system/back/login/auth.html";//跳转到H5授权界面
                velocityContext.put("jwid", jwids.get(0).getJwid());
                velocityContext.put("uid", loginUser.getId());
                velocityContext.put("username", loginUser.getUserId());
                ViewVelocity.view(request, response, viewName, velocityContext);
            }
        }


        ViewVelocity.view(request, response, viewName, velocityContext);
    }

    /**
     * 手机端获取菜单
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getMenu", method = { RequestMethod.GET, RequestMethod.POST })
    public AjaxJson getMenu(HttpServletRequest request) {
        AjaxJson json = new AjaxJson();
        LoginUser loginUser = getCurrentUser(request);
        if(loginUser == null) {
            json.setSuccess(false);
            json.setMsg("未获取到当前登录用户，请重新登录！");
            return json;
        }
        List<Menu> menuTree = jwSystemAuthService.getMenuTree(loginUser.getUserId());
        json.setMsg("查询成功");
        Map<String, Object> map = new HashMap<>();
        map.put("menu", menuTree);
        json.setObj(map);
        return json;
    }
}
